import { service } from './service'
import { config } from './config'
import { getAccessToken, getTenantId } from '@/utils/auth'
import errorCode from '@/config/axios/errorCode'

const { content_type } = config

export const generic_params = '_platform=web'

const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE === 'true'
export const generic_headers = () => {
  const headers = {}
  const accessToken = getAccessToken()
  if (accessToken) {
    headers['Authorization'] = 'Bearer ' + accessToken
  }
  if (tenantEnable) {
    const tenantId = getTenantId()
    if (tenantId) {
      headers['tenant-id'] = tenantId
    }
  } else {
    // 未开启租户时，可以传递0，配合验证租户id=0的场景，服务端未开启租户时也不影响
    headers['tenant-id'] = 0
  }
  return headers
}

export const response_err_msg = (resp_data: any) => {
  return resp_data.extensions?.realMessage || resp_data.msg || errorCode['default']
}

const request = (option: AxiosConfig) => {
  const { contentType, headers, ...otherOptions } = option
  return service({
    ...otherOptions,
    headers: {
      'content-type': contentType || content_type,
      ...headers
    }
  })
}

export default {
  get: async <T = any>(option: AxiosConfig) => {
    const res = await request({ method: 'GET', ...option })
    return res.data as unknown as T
  },
  getOriginal: async (option: AxiosConfig) => {
    return await request({ method: 'GET', ...option })
  },
  post: async <T = any>(option: AxiosConfig) => {
    const res = await request({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  postOriginal: async (option: AxiosConfig) => {
    return await request({ method: 'POST', ...option })
  },
  delete: async <T = any>(option: AxiosConfig) => {
    const res = await request({ method: 'DELETE', ...option })
    return res.data as unknown as T
  },
  put: async <T = any>(option: AxiosConfig) => {
    const res = await request({ method: 'PUT', ...option })
    return res.data as unknown as T
  },
  download: async <T = any>(option: AxiosConfig) => {
    const res = await request({ method: 'GET', responseType: 'blob', ...option })
    return res as unknown as Promise<T>
  },
  upload: async <T = any>(option: AxiosConfig) => {
    option.contentType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  uploadOriginal: async (option: AxiosConfig) => {
    option.contentType = 'multipart/form-data'
    return await request({ method: 'POST', ...option })
  }
}
